import React, { useEffect, useMemo, useState } from 'react';
import {
    Button,
    Cascader,
    DatePicker,
    Form,
    Input,
    InputNumber,
    Mentions,
    Select,
    TreeSelect,
    Image,
    message
} from 'antd';
import { categoryAdd, categoryUpdate, getCategoryList } from '@/api/category';
import { useRouter } from 'next/router';
import style from './index.module.css'
import Content from '../Content';
import { CategoryQueryList } from '@/type';

const level_options = [
    { label: '级别1', value: 1 },
    { label: '级别2', value: 2 }
]
export default function CategoryForm({ title, editData }: { title: string, editData: CategoryQueryList }) {
    const [form] = Form.useForm();
    const router = useRouter();
    const [levelOneList, setlevelOneOptions] = useState([])
    const [level, setLevel] = useState(1);
    const handleSubmit = () => {
        form.validateFields().then(async (values) => {
            if (editData) {
                const { _id }: any = editData
                await categoryUpdate(_id, values);
                message.success('更新成功');
                router.push('/category');
            } else {
                const res = await categoryAdd(values);
                message.success('创建成功');
                router.push('/category');
            }

        });
    }

    useEffect(() => {
        if (editData) {
            form.setFieldsValue({ ...editData })
        }
        async function fetchData() {
            const res = await getCategoryList();
            setlevelOneOptions(res.data);
        }
        fetchData();
    }, [title, editData])

    const levelOneOptions = useMemo(() => {
        return levelOneList.map((item: any) => ({
            label: item.name,
            value: item._id
        }))
    }, [levelOneList])

    return (
        <Content title={title}>
            <Form
                form={form}
                className={style.form}
                // {...formItemLayout}
                variant="filled"
                style={{ maxWidth: 600 }}
                onFinish={handleSubmit}>
                <Form.Item label="名称" name="name" rules={[{ required: true, message: 'Please input!' }]}>
                    <Input placeholder='请输入' />
                </Form.Item>
                <Form.Item name="level" label="级别" rules={[{ required: true, message: 'Please input!' }]}>
                    <Select placeholder='请输入' allowClear options={level_options} onChange={(val) => setLevel(val)} />
                </Form.Item>
                {level === 2 && <Form.Item name="parent" label="所属级别">
                    <Select placeholder='请输入' allowClear options={levelOneOptions} />
                </Form.Item>}
                <Form.Item>
                    <Button className={style.btn} type="primary" htmlType="submit">
                        {editData ? '更新' : '创建'}
                    </Button>
                </Form.Item>
            </Form>
        </Content>
    )
}
